<template>
  <!-- 自定义表单验证
          validator:(rule,value,callback)=>{
              rule:当前的验证规则
              value:当前验证项的值
              callback:如果验证允许通过  callback()  不能通过callback(new Error("错误信息"))
              注意点:任何if判断 都需要最后有一个callback
          }
        
        -->
  <el-dialog
    :visible.sync="isShow"
    width="600px"
    :show-close="false"
    class="register"
  >
    <div class="title" slot="title">
      用户注册
    </div>

    <el-form :model="form" label-width="80px" :rules="rules" ref="form">
      <!-- 头像上传 -->
      <el-form-item label="头像" class="uplod-img" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          name="image"
        >
          <img v-if="imageUrl" :src="baseUrl + '/' + imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"> </el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"> </el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"> </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"> </el-input>
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"> </el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img
              :src="baseUrl + codeUrl"
              alt=""
              class="code-img"
              @click="codeClick"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"> </el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button @click="getCode" :disabled="totalTime != 5"
              >获取用户验证码
              <span v-if="totalTime != 5"> {{ totalTime }} </span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div class="footer" slot="footer">
      <el-button type="primary" @click="subit">确 定</el-button>
      <el-button @click="isShow = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPhoneCode, toRegister } from '@/api/register.js'
export default {
  watch: {
    isShow () {
      if (this.isShow == false) {
        this.$refs.form.resetFields()
        this.imageUrl = ''
      }
    }
  },
  data () {
    return {
      totalTime: 5,
      form: {
        avatar: '', //	是	string	头像地址
        username: '', //	是	string	用户名
        email: '', //	是	string	邮箱
        phone: '', //	是	string	手机号
        password: '', //	是	string	密码
        code: '', //图形码
        rcode: '' //验证码
      },
      isShow: false,
      imageUrl: '',
      baseUrl: process.env.VUE_APP_URL,
      codeUrl: '/captcha?type=sendsms',
      rules: {
        avatar: [{ required: true, message: '请上传头像', trigger: 'change' }], //	是	string	头像地址
        username: [
          { required: true, message: '请输入昵称', trigger: 'change' }
        ], //	是	string	用户名
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请正确输入邮箱'))
              }
            },
            trigger: 'change'
          }
        ], //	是	string	邮箱
        phone: [
          { required: true, message: '请输入手机', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (reg.test(value)) {
                callback()
              } else {
                callback(new Error('请正确输入手机号'))
              }
            },
            trigger: 'change'
          }
        ], //	是	string	手机号
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ], //	是	string	密码
        code: [{ required: true, message: '请输入图形码', trigger: 'change' }], //图形码
        rcode: [{ required: true, message: '请输入验证码', trigger: 'change' }] //验证码
      }
    }
  },
  methods: {
    handleAvatarSuccess (res) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data.file_path
      this.form.avatar = res.data.file_path
      this.$refs.form.validateField(['avatar'])
      // console.log(res);
      // this.imageUrl = res.data.file_path
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或者png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //全局验证
    subit () {
      this.$refs.form.validate(result => {
        if (result) {
          toRegister(this.form).then(res => {
            console.log(res)
            this.isShow = false
            this.$message.success('注册成功')
          })
        } else {
          this.$message.error('验证失败')
        }
      })
    },
    //修改图形码
    codeClick () {
      this.codeUrl = '/captcha?type=sendsms&abcd=' + Date.now()
    },
    getCode () {
      let num = 0
      this.$refs.form.validateField(['phone', 'code'], err => {
        if (err == '') {
          num++
        }
      })
      if (num == 2) {
        // this.$axios({
        //   url: '/sendsms',
        //   method: 'post',
        //   data: {
        //     phone: this.form.phone,
        //     code: this.form.code
        //   }
        // })

        this.totalTime--
        let timeId = setInterval(() => {
          this.totalTime--
          if (this.totalTime == 0) {
            this.totalTime = 5
            clearInterval(timeId)
          }
        }, 1000)
        getPhoneCode({
          phone: this.form.phone,
          code: this.form.code
        }).then(res => {
          //console.log(res)
          this.$message.success(res.data.data.captcha + '')
        })
      } else {
        this.$message.error('请输入手机号码和图形码')
      }
    }
  }
}
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    text-align: center;
    background: linear-gradient(to right, #01c4fa, #1395fa);
    font-size: 14px;
    font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
    font-weight: 400;
    text-align: center;
    color: #fefefe;
    letter-spacing: 0px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .uplod-img {
    text-align: center;
  }
  .footer {
    text-align: center;
  }
  .code-img {
    width: 100%;
    height: 40px;
  }
}
</style>
